package com.xxjh.brs.scheduler;

import com.xxjh.brs.uavmodeling.service.UavModelingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.Instant;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

/**
 * @author CHENCHEN
 * @title 定时任务拉取FTP内容推送到另一台FTP服务
 * @company 新兴际华科技（天津）有限公司
 * @create 2024-07-03 19:21
 */
@Slf4j
@Service
public class FtpTransferDynamicScheduledService {

    private final ThreadPoolTaskScheduler taskScheduler;

    private final Map<String, ScheduledFuture<?>> taskFutures = new ConcurrentHashMap<>();

    @Autowired
    public FtpTransferDynamicScheduledService(ThreadPoolTaskScheduler scheduler) {
        this.taskScheduler = scheduler;
    }

    @Autowired
    private UavModelingService uavModelingService;

    public synchronized void startTask(String mapId, String taskId){
        uavModelingService.modelingStatus(mapId, taskId);
        Runnable taskRunner = () -> executeTask(mapId);
        if (taskFutures.containsKey(mapId) && !taskFutures.get(mapId).isCancelled()) {
            taskFutures.get(mapId).cancel(false);
            log.info("关闭已存在的任务 mapId : [{}]", mapId);
        }
        Instant startTime = Instant.now().plus(Duration.ofSeconds(10)); // 例如ofMinutes(1)，从现在起1分钟后开始
        ScheduledFuture<?> future = taskScheduler.scheduleWithFixedDelay(taskRunner, startTime, Duration.ofSeconds(60));
        taskFutures.put(mapId, future);
    }

    public void reloadTask(){
        uavModelingService.initChecking().forEach(mapId ->{
            startTask(mapId, null);
        });
    }

    public void stopModeling(String mapId){
        stopTask(mapId);
        uavModelingService.delFtpAndLocalDirectory(mapId);
    }

    private void executeTask(String mapId) {
        if(uavModelingService.transferFtp(mapId)){
            stopTask(mapId);
        }
    }

    protected synchronized void stopTask(String mapId) {
        ScheduledFuture<?> future = taskFutures.remove(mapId);
        if (future != null && !future.isCancelled()) {
            future.cancel(true);
        }
    }


}
